package de.homelabs.web.homelabs.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import de.homelabs.hlmodules.cms.configuration.service.HLConfigurationManager;
import de.homelabs.hlmodules.cms.realm.service.HLRealmService;

@Controller
public class ErrorHandler {

	@Autowired
	HLConfigurationManager hlConfigManager;
	
	@Autowired
	@Qualifier("hlRealmService")
	HLRealmService hlRealmService;
	
	@RequestMapping("/error.htm")
	public ModelAndView errorHandler(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// just do a response write
		response.getWriter().append("Some error occured:\n");
		response.getWriter()
				.append("ConfigManager has Errors: "
						+ hlConfigManager.getConfigurationByDomain(hlRealmService.getNormalizedDomain(request)).hasErrors() + "\n");
		response.getWriter().append(
				"ConfigManager Errors: "
						+ hlConfigManager.getConfigurationByDomain(hlRealmService.getNormalizedDomain(request)).getErrors()
								.toString() + "\n");

		response.getWriter()
				.append("Error Code: "
						+ request
								.getAttribute("javax.servlet.error.status_code"));
		Throwable throwable = (Throwable) request
				.getAttribute("javax.servlet.error.exception");
		if (throwable != null)
			response.getWriter().append(
					"Error Message: " + throwable.getLocalizedMessage());
		return null;
	}
}
